package com.wlb.tv;

import android.annotation.SuppressLint;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends AppCompatActivity {

    private ProgressBar mProgressBar;
    private WebView webView;
    private final int Menu_IP = 0;
    private final int Menu_ABOUT = 1;
    private final String TAG = "wlb";

    private String ip = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_fullscreen);
        mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
        webView = findViewById(R.id.webview);
        String ipAddress = SpUtil.getString(this, "ip");
        if (!TextUtils.isEmpty(ipAddress)) {
            if (ipAddress.length() > 7 && !ipAddress.substring(0, 7).equals("http://")) {
                ipAddress = "http://" + ipAddress;
            }
            ip = ipAddress;
            webView.loadUrl(ipAddress);
            webView.loadUrl("javascript:window.location.reload(true)");
        } else {
            showInputDialog();
        }
        Log.i(TAG, "ip ---> " + ip);
        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        webView.setWebViewClient(new WebViewClient());
//        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                //使用WebView加载显示url
//                view.loadUrl(url);
//                //返回true
//                return true;
//            }
//        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 70) {
                    if (mProgressBar.getVisibility() == View.VISIBLE) {
                        mProgressBar.setVisibility(View.GONE);
                    }
                } else {
                    mProgressBar.setProgress(newProgress);
                }
            }
        });
        webView.getSettings().setJavaScriptEnabled(true);
        //允许android调用javascript
        webView.getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= 21) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        Log.d("wlb", "onCreateOptionsMenu triggered!");
        menu.add(0, Menu_IP, 0, R.string.ip);
        menu.add(0, Menu_ABOUT, 0, R.string.about);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.destroy();
            webView = null;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        Log.d(TAG, String.format("item id = %d", item.getItemId()));
        switch (item.getItemId()) {
            case Menu_IP:
                showInputDialog();
                break;
            case Menu_ABOUT:
                Toast toast2 = Toast.makeText(this, "Menu_About triggered!", Toast.LENGTH_SHORT);
                toast2.show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showInputDialog() {
        /*@setView 装入一个EditView
         */
        final EditText editText = new EditText(this);
        editText.setHint(ip);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(this);
        inputDialog.setTitle(R.string.input_ip).setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                            webView.loadUrl(ip);
                            webView.loadUrl("javascript:window.location.reload(true)");
                        } else {
                            Toast.makeText(FullscreenActivity.this,
                                    editText.getText().toString(),
                                    Toast.LENGTH_SHORT).show();
                            String ipAddress = editText.getText().toString().trim().replace(" ", "");
                            if (ipAddress.length() > 7 && !ipAddress.substring(0, 7).equals("http://")) {
                                ipAddress = "http://" + ipAddress;
                            }
                            webView.loadUrl(ipAddress);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    webView.loadUrl("javascript:window.location.reload(true)");
                                }
                            },3000);
                            Log.i(TAG, "ipAddress ---> " + ipAddress);
                            SpUtil.putString(FullscreenActivity.this, "ip",
                                    ipAddress);
                        }
                    }
                }).show();
    }
}